#include "Map.h"
#include "Game.h"

#ifndef NO_MAP_LOADING

#include <stdio.h>
#include <stdlib.h>

int LoadMap(Map *map,char *mapfile)
{
	map->w=32;
	map->h=32;
	map->tiles=calloc(sizeof(MapTile),map->w*map->h);
	if(!map->tiles)
	{
		fprintf(stderr,"Out of memory");
		return 0;
	}

	FILE *fh=fopen(mapfile,"rb");
	if(!fh)
	{
		fprintf(stderr,"Couldn't load map %s",mapfile);
		FreeMap(map);
		return 0;
	}

	for(int i=0;i<NUM_MAP_TEXTURES;i++)
	{
		fread(map->texturenames[i],32,1,fh);
	}

	for(int y=0;y<map->h;y++)
	for(int x=0;x<map->w;x++)
	{
		unsigned char buf[32];
		fread(buf,32,1,fh);

		MapTile *tile=&map->tiles[x+y*map->w];
		tile->floor=(buf[0]<<8)+buf[1];
		tile->actualroof=(buf[2]<<8)+buf[3];
		if(tile->floor>tile->actualroof) tile->roof=tile->floor;
		else tile->roof=tile->actualroof;

		tile->darkness=buf[4];
		tile->gate=buf[5];

		tile->textures[0]=buf[9];
		tile->textures[1]=buf[13];
		tile->textures[2]=buf[17];
		tile->textures[3]=buf[21];
		tile->roofcol=buf[22];
		tile->floorcol=buf[23];
	}

	unsigned char buf[6];
	fread(buf,6,1,fh);
	map->start_y=(buf[0]<<8)|buf[1];
	map->start_x=(buf[2]<<8)|buf[3];
	map->start_angle=(buf[4]<<8)|buf[5];

	fclose(fh);

	return 1;
}

void FreeMap(Map *map)
{
	free(map->tiles);
}

#endif



int MapFloor(Map *map,int x,int y)
{
	if(x<0||x>=map->w||y<0||y>=map->h) return 0;
	return map->tiles[x+y*map->w].floor;
}

int MapRoof(Map *map,int x,int y)
{
	if(x<0||x>=map->w||y<0||y>=map->h) return 0;
	return map->tiles[x+y*map->w].roof;
}

int MapGate(Map *map,int x,int y)
{
	if(x<0||x>=map->w||y<0||y>=map->h) return 0;
	return map->tiles[x+y*map->w].gate;
}
